package alipay

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/smartwalle/alipay/v3"
	"go.uber.org/zap"
	"net/http"
	"order_bff/global"
	"order_bff/order_proto"
	"strconv"
)

// 生成支付链接
func GenerateAlipayUrl(c *gin.Context) {
	orderSn := c.PostForm("order_sn")
	if orderSn == "" {
		c.JSON(http.StatusNotFound, gin.H{
			"code": 0,
			"msg":  "订单编号不能为空",
			"data": nil,
		})
		return
	}
	// 必须，上一步中使用 RSA签名验签工具 生成的私钥
	client, err := alipay.New(global.ServerConfig.AliPayConfig.AppId, global.ServerConfig.AliPayConfig.PrivateKey, false)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": 0,
			"msg":  "支付宝实例化失败",
			"data": nil,
		})
		return
	}
	detail, err := global.OrderSrvConnect.OrderDetail(context.Background(), &order_proto.OrderRequest{
		OrderSn: orderSn,
	})
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": 0,
			"msg":  "获取订单失败",
			"data": nil,
		})
		return
	}
	var p = alipay.TradeWapPay{}
	total := strconv.FormatFloat(float64(detail.OrderInfo.Total), 'f', 2, 64)
	p.NotifyURL = "http://16ccbba3.r7.cpolar.top/o/v1/alipay/notify"
	p.ReturnURL = "http://10.3.189.13:8083/o/v1/alipay/return"
	p.Subject = "订单请支付" + detail.OrderInfo.Name
	p.OutTradeNo = detail.OrderInfo.OrderSn
	p.TotalAmount = total
	p.ProductCode = "QUICK_WAP_WAY"

	url, err := client.TradeWapPay(p)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": 0,
			"msg":  "拉取订单支付失败",
			"data": nil,
		})
		return
	}

	// 这个 payURL 即是用于打开支付宝支付页面的 URL，可将输出的内容复制，到浏览器中访问该 URL 即可打开支付页面。
	var payURL = url.String()
	fmt.Println(payURL)
	c.JSON(http.StatusOK, gin.H{
		"alipay_url": payURL,
	})
}

// 支付成功返回信息
func ReturnUrl(c *gin.Context) {
	orderSn := c.Query("out_trade_no")
	if orderSn == "" {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "订单编号不能为空",
			"data": nil,
		})
		return
	}
	detail, err := global.OrderSrvConnect.OrderDetail(context.Background(), &order_proto.OrderRequest{
		OrderSn: orderSn,
	})
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "获取订单失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": detail,
	})
}

// 支付成功 回调修改订单信息
func NotifyUrl(c *gin.Context) {
	tradeStatus := c.PostForm("trade_status")
	tradeNo := c.PostForm("trade_no")
	outTradeNo := c.PostForm("out_trade_no")
	if tradeStatus == "TRADE_SUCCESS" {
		_, err := global.OrderSrvConnect.UpdateOrder(context.Background(), &order_proto.UpdateOrderInfo{
			PayType: "1",
			Status:  tradeStatus,
			TradeNo: tradeNo,
			OrderSn: outTradeNo,
		})
		if err != nil {
			zap.S().Panic("更新状态订单失败")
			return
		}
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "success",
			"data": nil,
		})
	}
}
